import sys
sys.path.append(sys.path[0] + '/lib')

import re
import time
import random

from server import *
from game import *


class ComputerAutomaton:
	def __init__ (self, client):
		self.client = client
	
	def authenticate (self, game, player):
		self.client.send_request('POST', 'game', {'id': game})
		self.client.send_request('POST', 'player', {'id': player})
		self.myself = player
	
	def play (self):
		last = 0
		
		while True:
			self.client.send_request('GET', 'messages', {'start':last + 1})
			
			messages_nb = len(self.client.response['messages'])
			
			for m in self.client.response['messages']:
				last = m['id']
				if re.match('^Waiting for \[Player %s\] to choose a color\.$' % (self.myself), m['message']) != None:
					self.client.send_request('POST', 'color', {'value': Card.colors[random.randint(0, 3)]})
			
			if messages_nb > 0 or current_turn == self.myself:
				self.client.send_request('GET', 'game/turn')
				current_turn = self.client.response['game']['turn']
				
				self.client.send_request('GET', 'game/discard/top')
				top = Card(self.client.response['game']['discard']['top'])
				
				self.client.send_request('GET', 'player/cards')
				hand = self.client.response['player']['cards']
				
				play = None
				
				for c in hand:
					card = Card(c)
					
					if card == top:
						play = card
						break
					elif current_turn == self.myself:
						if top.isDrawTwo():
							if card.isDrawTwo():
								play = card
								break
							elif card.isWild():
								play = card
								break
						
						elif card.sameColour(top):
							play = card
							break
						
						elif card.sameFigure(top):
							play = card
							break
					
						elif card.isWildFour():
							play = card
							break
				
			
				if play != None:
					self.client.send_request('PUT', 'player/play', {'card':card.to_str()})
				elif current_turn == self.myself:
					self.client.send_request('PUT', 'player/draw')
				
			time.sleep(1)
	

if __name__ == '__main__':
	HOST, PORT = "localhost", 9999

	client = RESTClient()
	client.connect((HOST, PORT))
	
	auto = ComputerAutomaton(client)
	auto.authenticate(int(sys.argv[1]), int(sys.argv[2]))
	auto.play()